package com.study.springboot2.listener;

import org.apache.zookeeper.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
// ApplicationRunner使用SpringBoot搭建项目的时候，如果希望在项目启动完成之前，能够初始化一些操作
public class ZooKeeperApplicationRunner implements ApplicationRunner {
//ApplicationRunner与CommandLineRunner做的事情是一样的，也是在服务启动之后其run()方法会被自动地调用，
// 唯一不同的是ApplicationRunner会封装命令行参数，可以很方便地获取到命令行参数和参数值。
    @Value("${server.port}")
    private String serverPost;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        start();
    }

    private void start() throws IOException, KeeperException, InterruptedException {
        ZooKeeper zooKeeper = new ZooKeeper("192.168.134.100:2181", 50000, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println(event.getState().name());
            }
        });

        // 2.创建临时节点
        String s1 = zooKeeper.create("/mayikt1", "mayikt".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        System.out.println("s1:" + s1);
// 3.创建持久节点
        String s2 = zooKeeper.create("/mayikt2", "mayikt".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println("s2:" + s2);
// 4.创建持久节点带顺序
        String s3 = zooKeeper.create("/mayikt3", "mayikt".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
        System.out.println("s3:" + s3);
// 5.创建临时节点带顺序
        String s4 = zooKeeper.create("/mayikt4", "mayikt".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println("s4:" + s4);


        /**
         * ConnectionLossException: KeeperErrorCode = ConnectionLoss for /mayikt
         * 可能超时时间设置过短，将5000 改成50000 重新执行成功
         *
         * 创建节点要一级一级目录创建，比如要创建/abc/def
         * 要执行如下两步
         * zooKeeper.create("/abc", "mayikt".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
         * zooKeeper.create("/abc/def", "mayikt".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
         */

    }
}
